package com.cyt.web.controller.phone;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.redis.RedisService;
import com.cyt.base.util.AssociationConstant;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.ErrorCode;
import com.cyt.base.util.JwtTokenUtils;
import com.cyt.web.controller.base.PhoneController;
import com.cyt.work.association.model.po.WxAssociationSign;
import com.cyt.work.association.model.vo.WxAssociationNewDetailVo;
import com.cyt.work.association.model.vo.WxAssociationNewDetailVoC;
import com.cyt.work.association.service.WxAssociationNewDetailService;
import com.cyt.work.association.service.WxAssociationSignService;
import com.cyt.wx.model.po.WxEducationUser;
import com.cyt.wx.model.po.WxMember;
import com.cyt.wx.service.WxEducationUserService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@RestController
public class PhoneAssociationNewController extends PhoneController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private WxEducationUserService wxEducationUserService;
    @Autowired
    private WxAssociationNewDetailService wxAssociationNewDetailService;
    @Autowired
    private WxAssociationSignService wxAssociationSignService;

    /**
     * 登录页面
     */
    @RequestMapping(value = "/phone/associationnew/associationLogin")
    public ModelAndView questionLogin(String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView("/mobile/associationnew/associationLogin");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 登录
     */
    @RequestMapping(value = "/phone/associationnew/login", method = RequestMethod.POST)
    public ReturnResult login(String token, String applyId, String loginName, String password) {
        WxMember wxMember = acceptToken(token);
        ReturnResult loginResult = wxEducationUserService.login(wxMember, loginName, password);
        if (loginResult.getCode() == 0) {
            // 登录成功,加入jwt token
            // 需要人员类型
            WxEducationUser wxEducationUser = (WxEducationUser) loginResult.getData();
            String eduToken = JwtTokenUtils.createToken(wxEducationUser.getId(), wxEducationUser.getName(), wxEducationUser.getUserType(), true);
            loginResult.setData(eduToken);
        }
        return loginResult;
    }

    /**
     * 社团列表页面
     */
    @RequestMapping(value = "/phone/associationnew/associationList")
    public ModelAndView associationList(String token, String eduToken, String applyId) {
        // 如果token无法解析，则直接跳转至登录页面，说明token有误
        String userType;
        if (StringUtils.isEmpty(eduToken)) {
            Map<String, Object> map = acceptToken(token, applyId, APPLY_TYPE_STZX);
            if (!(Boolean) map.get("flag")) {
                return (ModelAndView) map.get("modelAndView");
            }
            // 需要userEdu的类型
            WxEducationUser wxEducationUser = (WxEducationUser) map.get("wxEducationUser");
            userType = wxEducationUser.getUserType();
            eduToken = JwtTokenUtils.createToken(wxEducationUser.getId(), wxEducationUser.getName(), wxEducationUser.getUserType(), true);
        } else {
            userType = JwtTokenUtils.getUserType(eduToken);
        }
        // 校验，如果没有登录，则跳转到登录页面
        ModelAndView modelAndView = new ModelAndView();
        if (StringUtils.equals(userType, BaseConstant.EDUCATION_USER_TYPE_TEACHER)) {
            modelAndView = new ModelAndView("/mobile/associationnew/teacherAssociationList");
        } else if (StringUtils.equals(userType, BaseConstant.EDUCATION_USER_TYPE_STUDENT)) {
            modelAndView = new ModelAndView("/mobile/associationnew/studentAssociationList");
        }
        modelAndView.addObject("token", token);
        modelAndView.addObject("eduToken", eduToken);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 社团详情页面
     */
    @RequestMapping(value = "/phone/associationnew/associationDetail")
    public ModelAndView associationDetail(String token, String eduToken, String applyId, String associationId, String associationNewId,
                                    String associationNewDetailId, String type, String signId) {
        //type =1 为学生 type =2 为老师
        ModelAndView modelAndView = new ModelAndView("/mobile/associationnew/associationDetail");
        modelAndView.addObject("token", token);
        modelAndView.addObject("eduToken", eduToken);
        modelAndView.addObject("applyId", applyId);
        modelAndView.addObject("associationId", associationId);
        modelAndView.addObject("signId", signId);
        modelAndView.addObject("type", type);
        modelAndView.addObject("associationNewId", associationNewId);
        modelAndView.addObject("associationNewDetailId", associationNewDetailId);
        return modelAndView;
    }

    /**
     * 教师社团列表界面
     */
    @RequestMapping(value = "/phone/associationnew/teacherAssociationList")
    public ModelAndView teacherAssociationList(String token, String applyId) {
        ModelAndView modelAndView = new ModelAndView("/mobile/associationnew/associationDetail");
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        return modelAndView;
    }

    /**
     * 获取社团报名列表(学生)
     */
    @RequestMapping(value = "/phone/associationnew/leftJson")
    public ReturnResult questionJsonList(String eduToken) {
        String userId = JwtTokenUtils.getUserId(eduToken);
        // 缓存，1、缓存每个社团的数据，基本数据及数目，2、缓存每个学生的社团数目一个list，学生的报名数目
        String detailIds = redisService.hget(AssociationConstant.WX_ASSOCIATION_NEW_STU, userId);
        List<WxAssociationNewDetailVoC> detailList = JSONArray.parseArray(detailIds, WxAssociationNewDetailVoC.class);
        if (CollUtil.isEmpty(detailList)) {
            PageInfo<WxAssociationNewDetailVo> page = new PageInfo<>();
            return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
        }
        // 查询每个社团基本数据及报名信息
        for (WxAssociationNewDetailVoC detail : detailList) {
            // 获取社团详情
            // String detailStr = redisService.get(AssociationConstant.WX_ASSOCIATION_NEW_DETAIL + detail.getId());
            // 已报名数量
            String detailNum = redisService.get(AssociationConstant.WX_ASSOCIATION_NEW_DETAIL_NUM + detail.getId());
            // 剩余数量
            int i = Integer.parseInt(detail.getTotalNumber()) - Integer.parseInt(detailNum);
            detail.setStuNumber(String.valueOf(i));
        }
        PageInfo<WxAssociationNewDetailVoC> page = new PageInfo<>(detailList);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    @RequestMapping(value = "/phone/associationnew/leftJsonSql")
    public ReturnResult questionJsonListSql(String eduToken, int pageSize, int pageNum) {
        String userId = JwtTokenUtils.getUserId(eduToken);
        ReturnResult returnResult = wxAssociationNewDetailService.pageLeft(userId, pageSize, pageNum);
        return returnResult;
    }

    /**
     * 获取社团报名列表(学生)
     * 学生报名的社团
     */
    @RequestMapping(value = "/phone/associationnew/rightJson")
    public ReturnResult rightJson(String eduToken, int pageSize, int pageNum) {
        String userId = JwtTokenUtils.getUserId(eduToken);
        return wxAssociationSignService.findDetailVoByUserPage(userId, pageSize, pageNum);
    }

    /**
     * 获取社团详情
     */
    @RequestMapping(value = "/phone/associationnew/getAssociationDetail")
    public ReturnResult getAssociationDetail(String eduToken, String associationNewDetailId, String associationNewId) {
        String userId = JwtTokenUtils.getUserId(eduToken);
        String detailStr = redisService.get(AssociationConstant.WX_ASSOCIATION_NEW_DETAIL + associationNewDetailId);
        WxAssociationNewDetailVoC wxAssociationNewDetailVo = JSON.toJavaObject(JSON.parseObject(detailStr), WxAssociationNewDetailVoC.class);
        // 根据id 获取社团详情,缓存中的详情，还需要查看缓存中是否报名，以及是否入库
        // 查询是否有报名记录
        WxAssociationSign wxAssociationSign = new WxAssociationSign();
        wxAssociationSign.setAssociationNewId(associationNewId);
        wxAssociationSign.setAssociationDetailId(associationNewDetailId);
        wxAssociationSign.setAssociationUserId(userId);
        List<WxAssociationSign> list = wxAssociationSignService.select(wxAssociationSign);
        if (CollUtil.isNotEmpty(list)) {
            wxAssociationNewDetailVo.setSignId(list.get(0).getId());
        } else {
            wxAssociationNewDetailVo.setSignId("");
        }
        return new ReturnResult(wxAssociationNewDetailVo);
    }

    /**
     * 社团报名
     */
    @RequestMapping(value = "/phone/associationnew/associationNewSign", method = RequestMethod.POST)
    // @Limit(10)
    public ReturnResult addOrUpdate(String applyId, String eduToken, String associationId, String associationNewId, String associationNewDetailId){
        String userId = JwtTokenUtils.getUserId(eduToken);
        return wxAssociationSignService.associationNewSign(userId, applyId, associationId, associationNewId, associationNewDetailId);
    }

    /**
     * 社团报名-threadpool
     */
    @RequestMapping(value = "/phone/associationnew/associationNewSignT", method = RequestMethod.POST)
    public ReturnResult associationNewSignT(String applyId, String eduToken, String associationId, String associationNewId, String associationNewDetailId){
        String userId = JwtTokenUtils.getUserId(eduToken);
        return wxAssociationSignService.associationNewSignT(userId, applyId, associationId, associationNewId, associationNewDetailId);
    }

    /**
     * 社团报名-rabbit队列
     */
    @RequestMapping(value = "/phone/associationnew/associationNewSignR", method = RequestMethod.POST)
    // @Limit(50)
    public ReturnResult associationNewSignR(String applyId, String eduToken, String associationId, String associationNewId, String associationNewDetailId){
        String userId = JwtTokenUtils.getUserId(eduToken);
        return wxAssociationSignService.associationNewSignR(userId, applyId, associationId, associationNewId, associationNewDetailId);
    }

    @RequestMapping(value = "/phone/associationnew/associationWait")
    public ModelAndView associationWait(String token, String applyId, String eduToken, String associationId, String signId,
                                        String associationNewId, String associationNewDetailId) {
        ModelAndView modelAndView = new ModelAndView("/mobile/associationnew/associationWait");
        modelAndView.addObject("eduToken", eduToken);
        modelAndView.addObject("signId", signId);
        modelAndView.addObject("token", token);
        modelAndView.addObject("applyId", applyId);
        modelAndView.addObject("associationId", associationId);
        modelAndView.addObject("associationNewId", associationNewId);
        modelAndView.addObject("associationNewDetailId", associationNewDetailId);
        return modelAndView;
    }

    @RequestMapping(value = "/phone/associationnew/getAssociationBySignId")
    public ReturnResult getAssociationBySignId(String eduToken, String signId, String associationNewId, String associationNewDetailId) {
        String userId = JwtTokenUtils.getUserId(eduToken);
        // 查询redis是否存在信息
        if (!redisService.exists(AssociationConstant.WX_ASSOCIATION_NEW_STU_DETAIL + associationNewDetailId +  "_" + userId)) {
            // 报名失败
            return new ReturnResult(ErrorCode.CODE_1, BaseConstant.ASSOCITATION_SIGN_ERROR_AGAIN);
        }
        WxAssociationSign wxAssociationSign = wxAssociationSignService.selectByPrimaryKey(signId);
        if (wxAssociationSign == null) {
            // 已报名成功，但是，未入库,10
            return new ReturnResult(ErrorCode.CODE_10, BaseConstant.ASSOCITATION_SIGN_LOADING);
        }
        return new ReturnResult(wxAssociationSign);
    }

    /**
     * 社团退团
     */
    @RequestMapping(value = "/phone/associationnew/associationNewQuit", method = RequestMethod.POST)
    public ReturnResult associationNewQuit(String eduToken, String associationNewId, String associationNewDetailId, String signId) {
        String userId = JwtTokenUtils.getUserId(eduToken);
        return wxAssociationSignService.associationNewQuit(userId, associationNewId, associationNewDetailId, signId);
    }

    /**
     * 查询社团已报人数
     */
    @RequestMapping(value = "/phone/associationnew/hasAssSignPage", method = RequestMethod.POST)
    public ReturnResult hasAssSignPage(String associationNewDetailId, int pageSize, int pageNum) {
        return wxAssociationSignService.findVoHasSignPage(associationNewDetailId, pageSize, pageNum);
    }

    /**
     * 获取教师所带社团
     */
    @RequestMapping(value = "/phone/associationnew/getTeacherAssocaitionList")
    public ReturnResult getTeacherAssocaitionList(String eduToken, int pageSize, int pageNum) {
        String userId = JwtTokenUtils.getUserId(eduToken);
        // 老师
        WxEducationUser wxEducationUser = wxEducationUserService.selectByPrimaryKey(userId);
        return wxAssociationNewDetailService.findDetailVoListByTeacher(wxEducationUser.getUserNumber(), pageSize, pageNum);
    }
}
